package hst;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class HalfSextupleTown extends JPanel {
	private static final long serialVersionUID = 8740920860714699390L;
	
	private int placementValue;
	
	private JPanel top;
	private JPanel main;

	private JLabel scoreLabel;
	private JLabel placementValueLabel;
	private Town town;
	
	private JButton[][] buttonGrid;
	
	public HalfSextupleTown() {
		super(new BorderLayout());
		
		town = new Town();
		
		placementValue = getNextValue();
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {}

		add(top = new JPanel(), BorderLayout.NORTH);
		add(main = new JPanel(new GridLayout(Town.GRID_WIDTH, Town.GRID_HEIGHT)), BorderLayout.CENTER);
		
		top.setPreferredSize(new Dimension(768, 128));
		main.setPreferredSize(new Dimension(768, 768));

		top.add(scoreLabel = new JLabel("Score: " + town.getScore()));
		top.add(placementValueLabel = new JLabel("Next: " + placementValue));
		
		buttonGrid = new JButton[Town.GRID_WIDTH][Town.GRID_HEIGHT];
		
		for(int y = 0; y < Town.GRID_HEIGHT; y++) {
			for(int x = 0; x < Town.GRID_WIDTH; x++) {
				final int tx = x;
				final int ty = y;
				buttonGrid[x][y] = new JButton(town.getValue(x, y) + "");
				main.add(buttonGrid[x][y]);
				buttonGrid[x][y].addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						gridClick(tx, ty);
					}
				});
			}
		}
	}
	
	private void gridClick(int x, int y) {
		if(town.canPlace(x, y, placementValue)) {
			town.setValue(x, y, placementValue);
			
			placementValue = getNextValue();
			
			updateGUI();
		}
	}
	
	private void updateGUI() {
		placementValueLabel.setText("Next: " + placementValue);
		scoreLabel.setText("Score: " + town.getScore());
		
		for(int y = 0; y < Town.GRID_HEIGHT; y++) {
			for(int x = 0; x < Town.GRID_WIDTH; x++) {
				buttonGrid[x][y].setText(town.getValue(x, y) + "");
			}
		}
	}
	
	private int getNextValue() {
		double val = Math.random();
		return (int)(val * val * val * 3 + 1);
	}
	
	public static void main(String[] args) {
		JFrame frame = new JFrame("Half Sextuple Town");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new HalfSextupleTown());
		frame.pack();
		frame.setVisible(true);
	}
}
